﻿using System.Configuration;
using System.Reflection;
using System.ServiceModel.Configuration;

namespace ConsoleApplicationSvc
{
    /// <summary>
    /// This class is used to create ".svc" files.
    /// Remember to copy current "app.config" file from Services to under this project.
    /// </summary>
    public class SvcCreator
    {
        public SvcCreator()
        {
        }

        public string CreateSvcFiles()
        {
            System.Configuration.Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
            ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");

            string svcCreationPath = string.Empty;

            foreach (ServiceElement currentservice in svcmod.Services.Services)
            {
                string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
                appPath = appPath.Replace("\\bin\\Debug", "").Replace("\\bin\\Release", "");

                svcCreationPath = string.Format(@"{0}\SVC\", appPath);

                string serviceFullName = currentservice.Name;
                int startIndex = serviceFullName.LastIndexOf('.') + 1;
                int length = serviceFullName.Length - startIndex;
                string serviceName = serviceFullName.Substring(startIndex, length);

                string filename = string.Format(@"{0}{1}.svc", svcCreationPath, serviceName);

                if (!System.IO.Directory.Exists(svcCreationPath)) System.IO.Directory.CreateDirectory(svcCreationPath);

                System.IO.FileStream fs = System.IO.File.Open(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);

                sw.WriteLine(string.Format("<% @ServiceHost Language=\"C#\" Debug=\"true\" Service=\"{0}\" %>", serviceFullName));
                sw.Close();
                sw = null;
            }

            return svcCreationPath;
        }
    }
}
